import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:short_video/ui/widgets/custom_network_image.dart';
import 'package:short_video/utils/asset_util.dart';
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_player/video_player.dart';
import '../../../utils/color_util.dart';
import '../../../view_model/publish/publish_view_model.dart';
import '../../widgets/custom_scaffold.dart';

class PublishPage extends StatefulWidget {
  const PublishPage({Key? key}) : super(key: key);
  @override
  State<PublishPage> createState() => _PublishPageState();
}

class _PublishPageState extends State<PublishPage> {
  // ImagePicker获取内容后返回的对象是XFile
  XFile? video;

  // 使用ImagePicker前必须先实例化
  final ImagePicker _picker = ImagePicker();
  VideoPlayerController? _controller;
  VideoPlayerController? _toBeDisposed;
  String? _retrieveDataError;

  //选择视频
  void selectVideo(ImageSource source) async {
    video = await _picker.pickVideo(
      source: source,
      maxDuration: const Duration(seconds: 60),  //最大视频时长60s
    );
    _playVideo(video);
  }

  Future<void> _playVideo(XFile? file) async {
    if (file != null && mounted) {
      await _disposeVideoController();
      late VideoPlayerController controller;

      controller = VideoPlayerController.file(File(file.path));

      _controller = controller;
      final double volume = kIsWeb ? 0.0 : 1.0;
      await controller.setVolume(volume);
      await controller.initialize();
      //await controller.setLooping(true);
      await controller.play();
      setState(() {});
    }
  }

  Future<void> _disposeVideoController() async {
    if (_toBeDisposed != null) {
      await _toBeDisposed!.dispose();
    }
    _toBeDisposed = _controller;
    _controller = null;
  }

  Widget _previewVideo() {
    final Text? retrieveError = _getRetrieveErrorWidget();
    if (retrieveError != null) {
      return retrieveError;
    }
    if (_controller == null) {
      return const Text(
        'You have not yet picked a video',
        textAlign: TextAlign.center,
      );
    }
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: AspectRatioVideo(_controller),
    );
  }

  Text? _getRetrieveErrorWidget() {
    if (_retrieveDataError != null) {
      final Text result = Text(_retrieveDataError!);
      _retrieveDataError = null;
      return result;
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (BuildContext context) => PublishViewModel(),
      child: Consumer<PublishViewModel>(builder: (context, viewModel, child) {
        return CustomScaffold(
          context: context,
          title: "发布",
          actions: [
            GestureDetector(
              child: AssetUtil.svgImage("other/send",
                  size: const Size(28, 28), color: ColorsUtil.COLOR_AAAAAA),
              behavior: HitTestBehavior.opaque,
              onTap: () {
                viewModel.publish(context,video!);
              },
            )
          ],
          elevation: 0.2,
          backgroundColor: ColorsUtil.COLOR_333333,
          child: _buildContent(viewModel),
        );
      }),
    );
  }

  Future<void> retrieveLostData() async {
    final LostDataResponse response = await _picker.retrieveLostData();
    if (response.isEmpty) {
      return;
    }
    if (response.file != null) {
      if (response.type == RetrieveType.video) {
        await _playVideo(response.file);
      }
    } else {
      _retrieveDataError = response.exception!.code;
    }
  }


  Widget _buildContent(PublishViewModel viewModel) {
    return Container(
      padding: const EdgeInsets.only(top: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            padding: const EdgeInsets.only(left: 16, right: 16),
            height: 100,
            decoration: BoxDecoration(
                borderRadius: const BorderRadius.all(Radius.circular(10)),
                border: Border.all(
                    color: ColorsUtil.COLOR_666666,
                    width: 0.5,
                    style: BorderStyle.solid)),
            child: TextField(
              keyboardType: TextInputType.text,
              style:
              const TextStyle(fontSize: 16, color: ColorsUtil.COLOR_F7F8FA),
              controller: viewModel.introduceController,
              cursorHeight: 16,
              cursorColor: ColorsUtil.COLOR_666666,
              decoration: const InputDecoration(
                isCollapsed: false,
                border: InputBorder.none,
                hintText: "请输入合适的作品介绍，让更多的人看到",
                hintStyle:
                TextStyle(fontSize: 16, color: ColorsUtil.COLOR_999999),
              ),
              keyboardAppearance: Brightness.light,
              onChanged: (value) {},
            ),
          ),
          const SizedBox(height: 1),
          Expanded(
            child: Padding(
              padding: EdgeInsets.all(1),
              child: Container(
                width: double.infinity,
                child:defaultTargetPlatform == TargetPlatform.android?FutureBuilder<void>(
                  future: retrieveLostData(),
                  builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
                    switch (snapshot.connectionState) {
                      case ConnectionState.none:
                      case ConnectionState.waiting:
                        return const Text(
                          'You have not yet picked a video.',
                          textAlign: TextAlign.center,
                        );
                      case ConnectionState.done:
                        return _previewVideo();
                      default:
                        if (snapshot.hasError) {
                          return Text(
                            'Pick video error: ${snapshot.error}}',
                            textAlign: TextAlign.center,
                          );
                        } else {
                          return const Text(
                            'You have not yet picked a video.',
                            textAlign: TextAlign.center,
                          );
                        }
                    }
                  },
                ): _previewVideo(),
              ),
            ),),
          Row(mainAxisAlignment: MainAxisAlignment.center, children: [
            Padding(
              padding: const EdgeInsets.only(bottom: 16.0),
              child: FloatingActionButton(
                backgroundColor: Color(0xff363741),
                onPressed: () {
                  selectVideo(ImageSource.gallery);

                  // isVideo = true;
                  // _onImageButtonPressed(ImageSource.gallery);
                },
                heroTag: 'video0',
                tooltip: 'Pick Video from gallery',
                child: const Icon(Icons.video_library),
              ),
            ),
            SizedBox(
              width: 15.0,
            ),
            Padding(
              padding: const EdgeInsets.only(bottom: 16.0),
              child: FloatingActionButton(
                backgroundColor: Color(0xff363741),
                onPressed: () {
                  selectVideo(ImageSource.camera);
                  // isVideo = true;
                  // _onImageButtonPressed(ImageSource.camera);
                },
                heroTag: 'video1',
                tooltip: 'Take a Video',
                child: const Icon(Icons.videocam),
              ),
            ),
          ]),
        ],
      ),
    );
  }
}


class AspectRatioVideo extends StatefulWidget {
  AspectRatioVideo(this.controller);

  final VideoPlayerController? controller;

  @override
  AspectRatioVideoState createState() => AspectRatioVideoState();
}

class AspectRatioVideoState extends State<AspectRatioVideo> {
  VideoPlayerController? get controller => widget.controller;
  bool initialized = false;

  void _onVideoControllerUpdate() {
    if (!mounted) {
      return;
    }
    if (initialized != controller!.value.isInitialized) {
      initialized = controller!.value.isInitialized;
      setState(() {});
    }
  }

  @override
  void initState() {
    super.initState();
    controller!.addListener(_onVideoControllerUpdate);
  }

  @override
  void dispose() {
    controller!.removeListener(_onVideoControllerUpdate);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (initialized) {
      return Center(
        child: AspectRatio(
          aspectRatio: controller!.value.aspectRatio,
          child: VideoPlayer(controller!),
        ),
      );
    } else {
      return Container();
    }
  }
}